package com.webamc.util;

import com.db4o.Db4o;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.query.Query;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.List;

/**
 * Date: Mar 10, 2009
 * Time: 2:16:14 AM
 */
public class DB4OUtil {
    private static Logger log = Logger.getLogger(DB4OUtil.class);
    private static ObjectContainer db;

    public void setDbFile(String dbFile) {
        if (db == null) {
            db = Db4o.openFile(dbFile);
        } else {
            db.close();
            db = Db4o.openFile(dbFile);
        }
    }

    public static List select(Object prototype) {
        List list = new ArrayList();
        ObjectSet result = db.get(prototype);
        while (result.hasNext()) {
            list.add(result.next());
        }
        log.info("returning list=" + list);
        return list;
    }

    public static void delete() {

    }

    public static boolean update(Object c) {
        return insert(c);
    }

    public static boolean insert(Object c) {
        try {
            db.store(c);
            db.commit();
            log.info("saved-" + c);
            return true;
        } catch (Exception e) {
            log.error("Error saving-" + c + ", Error=" + e.getMessage(), e);
            db.rollback();
            return false;
        }
    }


    public static void listResult(ObjectSet<? extends Object> result) {
        log.info(result.size());
        while (result.hasNext()) {
            log.info(result.next());
        }
    }

    public static int clear() {
        Query q = db.query();
        ObjectSet results = q.execute();
        int counter = 0;
        while (results.hasNext()) {
            Object ob = results.next();
            //log.info(ob);
            db.delete(ob);
            counter++;
        }
        db.commit();
        return counter;
    }

    public static int clear(Class aClass) {
        List results = db.query(aClass);
        int counter = 0;
        for (Object o : results) {
            db.delete(o);
            counter++;
        }
        return counter;
    }

    public static List getAll(Class aClass) {
        List results = db.query(aClass);
        return results;
    }

    public static int dump() {
        log.info("DUMPING: " + db.ext().identity());
        Query q = db.query();
        List<? extends Object> results = q.execute();
        int counter = 0;
        for (Object o : results) {
            log.info("object: " + o);
            counter++;
        }
        log.info("END DUMP: " + db.ext().identity());
        return counter;
    }
}


